<template>
  <div class="canvas-container">
    <canvas ref="canvasId" />
    <h3>饼状图</h3>
  </div>
</template>

<script>
export default {
  mounted() {
    const arr = [20, 30, 40, 10, 50];
    this.draw(arr);
  },
  methods: {
    draw(arr) {
      //创建画布
      const canvasCon = document.querySelector(".canvas-container");
      const canvas = this.$refs["canvasId"];
      const canvasWidth = canvasCon.clientWidth;
      const canvasHeight = canvasCon.clientWidth;
      canvas.width = canvasWidth;
      canvas.height = canvasHeight;
      const ctx = canvas.getContext("2d");

      const x = canvasWidth * 0.5;
      const y = canvasWidth * 0.5;
      const r = canvasWidth * 0.3;
      ctx.arc(x, y, r, 0, Math.PI*2, false)
      ctx.strokeStyle = "#cccccc";
      ctx.stroke();
      
      function drawItem(sAngle,eAngle){
        //本次： sAngle 起始位置 和  eAngle 结束位置
        ctx.beginPath();
        ctx.arc(x, y, r,sAngle - Math.PI/2,eAngle - Math.PI/2, false);
        ctx.lineTo(x, y);
        ctx.fillStyle = '#'+parseInt(Math.random()*0xffffff).toString(16)
        ctx.fill();
      }

      const total = arr.reduce((total, next) => total + next);
      let sAngle = 0
      arr.forEach(item=>{
        let eAngle = sAngle + (item/total)*Math.PI*2
        drawItem(sAngle,eAngle)
        sAngle = eAngle
      })
    },
  },
};
</script>
<style lang="scss" scoped>
</style>